package com.example.walled_houses.utils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class LoginInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, Object> map = new HashMap<>();
        // TODO 判断是否需要拦截（ThreadLocal中是否有用户）
        if(UserHolder.getUser() == null){
            // TODO 没有，需要拦截设置状态码
            map.put("code", "202");
            map.put("data", null);
            map.put("msg", "token无效！");
            // 将map转为json
            String json = new ObjectMapper().writeValueAsString(map);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().println(json);
            // 拦截
            return false;
        }
        return true;
    }


}
